/*
  Name:        test08.Gray.Scale.Processing.cpp
  Copyright:   Version 0.1
  Author:      Rodrigo Luis de Souza da Silva
  Date:        04/07/2009
  Description: Load an image from file and convert it to grayscale.
               After that, make a small smooth for testing purposes.

*/

#include "pixelMap.h"
#ifdef WIN32
#include <windows.h>
#endif
#include <GL/glut.h>
#include <stdlib.h>

// Image Object
PixelMap *img = NULL;

void idle()
{
   glutPostRedisplay();
}

static void display(void)
{
   glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
   img->ViewImage();
   glutSwapBuffers();
}

static void key(unsigned char key, int x, int y)
{
   switch (key)
   {
      case 27 :
      case 'q':
         exit(0);
      break;
   }
   glutPostRedisplay();
}

void modifyImage(int iteractions = 1)
{
   int i, j;

   if(img)
   {
      pixel **pixels;
      // Aloca dinamicamente as linhas da matriz
      pixels = (pixel **) malloc(img->GetHeight() * sizeof(pixel *));
      // Aloca dinamicamente as colunas da matriz
      for(i = 0; i < img->GetHeight(); i++)
         pixels[i] = (pixel *) malloc(img->GetWidth() * sizeof(pixel));

      img->ConvertDataToPixels(pixels);

      for(int ite = 0; ite < iteractions; ite++)
         for(i = 1; i < img->GetHeight()-1; i++)
            for(j = 1; j < img->GetWidth()-1; j++)
               pixels[i][j].value = (pixels[i-1][j].value + pixels[i][j-1].value +
                                     pixels[i+1][j].value + pixels[i][j+1].value)/4;

      img->ConvertPixelsToData(pixels);

   }
}

int main(int argc, char *argv[])
{
   glutInit(&argc, argv);

   img = new PixelMap("resources//lena.bmp");

   // Convert stored bitmap to grayscale
   img->ConvertToGrayScale();

   // Simple Smooth in a local function
   modifyImage(20);

   glutInitWindowSize(img->GetWidth(),img->GetHeight());
   glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH);

   glutCreateWindow("GrayScale Test");

   glutKeyboardFunc(key);
   glutIdleFunc( idle);
   glutDisplayFunc(display);

   glutMainLoop();

   return 1;
}
